import React, {useEffect, useState} from "react";
import { get, trim } from "lodash";
import Modal from "antd/lib/modal";
import Form from "antd/lib/form";
import Input from "antd/lib/input";
import Select from "antd/lib/select";
import Checkbox from "antd/lib/checkbox";
import FileButton from "./FileButton";
import { wrap as wrapDialog, DialogPropType } from "@/components/DialogWrapper";
import DynamicComponent from "@/components/DynamicComponent";
import {policy} from "@/services/policy";
import Portal from "@/services/portal";
import notification from "@/services/notification";

function CreatePortalDialog({dialog, portalCode}) {
  const isCreatePortalEnabled = policy.isAdmin();
  const [code, setCode] = useState(portalCode || "");
  const [name, setName] = useState("");
  const [bgTitle, setBgTitle] = useState("");
  const [bgColor, setBgColor] = useState("");
  const [titleColor, setTitleColor] = useState("");
  const [bgStyle, setBgStyle] = useState("");
  const [isBuiltin, setIsBuiltin] = useState(false);
  const [isForbidStyle, setIsForbidStyle] = useState(false);
  const [isHiddenTitle, setIsHiddenTitle] = useState(false);
  const [portalStyle, setPortalStyle] = useState("dropdown");
  const [portalAuto, setPortalAuto] = useState(false);
  const [PortalHide, setPortalHide] = useState(false);
  const [colorStyleMode, setColorStyleMode] = useState('');
  const [isLoad, setIsLoad] = useState(false);
  const [isValid, setIsValid] = useState(false);
  const [saveInProgress, setSaveInProgress] = useState(false);

  function handleCodeChange(event) {
    const value = event.target.value.replace(/[^0-9a-zA-z]/g, '');
    setCode(value);
    setIsValid(value !== "" && name !== "");
  }

  function handleNameChange(event) {
    const value = trim(event.target.value);
    setName(value);
    setIsValid(value !== "" && code !== "");
  }

  function handleSubmit() {
    setSaveInProgress(true);

    let options ={
      bg: bgStyle, bgColor, titleColor, bgTitle, 
      colorStyleMode, portalStyle, portalAuto, 
      PortalHide, isHiddenTitle, isForbidStyle
    }

    if (portalCode !== "") {
      Portal.save(portalCode, {name: name, is_builtin: isBuiltin, options}).then(() => {
        dialog.close({ success: true});
      }).catch(error => {
        notification.error(get(error, "response.data.message", "保存失败！"));
        setSaveInProgress(false);
      });
    } else {
      Portal.create({code: code, name: name, is_builtin: isBuiltin, options}).then(() => {
        dialog.close({ success: true});
      }).catch(error => {
        notification.error(get(error, "response.data.message", "保存失败！"));
        setSaveInProgress(false);
      });
    }
  }

  useEffect(() => {
    if (portalCode !== "") {
      Portal.get(portalCode).then(rs => {
        if (rs) {
          setName(rs.name);
          setIsBuiltin(rs.is_builtin);
          if (rs.options) {
            if (rs.options.bgTitle) setBgTitle(rs.options.bgTitle);
            if (rs.options.bg) setBgStyle(rs.options.bg);
            if (rs.options.bgColor) setBgColor(rs.options.bgColor);
            if (rs.options.titleColor) setTitleColor(rs.options.titleColor);
            if (rs.options.isHiddenTitle) setIsHiddenTitle(rs.options.isHiddenTitle);
            if (rs.options.colorStyleMode) setColorStyleMode(rs.options.colorStyleMode);
            if (rs.options.portalStyle) setPortalStyle(rs.options.portalStyle);
            if (rs.options.portalAuto) setPortalAuto(rs.options.portalAuto);
            if (rs.options.PortalHide) setPortalHide(rs.options.PortalHide);
            if (rs.options.isForbidStyle) setIsForbidStyle(rs.options.isForbidStyle);
          }
          setIsValid(true);
        }
        setIsLoad(true);
      }).catch();
    } else {
      setIsLoad(true);
    }
  }, [portalCode]);

  return isLoad && (
    <Modal
      {...dialog.props}
      {...(isCreatePortalEnabled ? {} : { footer: null })}
      maskClosable = {false}
      title="门户类型"
      okText="保存"
      cancelText="取消"
      okButtonProps={{
        disabled: !isValid || saveInProgress,
        loading: saveInProgress,
        "data-test": "DashboardSaveButton",
      }}
      cancelButtonProps={{
        disabled: saveInProgress,
      }}
      onOk={handleSubmit}
      closable={!saveInProgress}
      wrapProps={{
        "data-test": "CreateDashboardDialog",
      }}>
      <DynamicComponent name="CreatePortalDialogExtra" disabled={!isCreatePortalEnabled}>
      <Form>
        <Form.Item label="编码">
          <Input
            defaultValue={code}
            onChange={handleCodeChange}
            placeholder="编码"
            disabled={saveInProgress || portalCode !== ""}
            autoFocus
          />
        </Form.Item>
        <Form.Item label="名称">
          <Input
            defaultValue={name}
            onChange={handleNameChange}
            placeholder="名称"
            disabled={saveInProgress}
          />
        </Form.Item>
        <Form.Item label="个性Logo">
          <Input
            value={bgStyle}
            onChange={(e) => setBgStyle(e.target.value)}
            placeholder="Logo图片"
            disabled={saveInProgress}
          />
          <FileButton doneEventHandler={value => setBgStyle(value)} position="left top" />
          <br/>
            <a href="https://www.dazdata.com/docs/use/16.html" target="_blank" rel="noopener noreferrer">官网指南</a>
            例：url("/static/images/dark/titlebg.png") no-repeat left top
        </Form.Item>
        <Form.Item label="个性标题">
          <Input
            value={bgTitle}
            onChange={(e) => setBgTitle(e.target.value)}
            placeholder="门户标题"
            disabled={saveInProgress}
          />
          <br/><br/>
          <Checkbox
            name="is_hidden"
            checked={isHiddenTitle}
            onChange={(e) => setIsHiddenTitle(e.target.checked)}>
            隐藏报表标题
          </Checkbox>
        </Form.Item>
        <Form.Item label="个性颜色">
          <Input
            style={{width: "50%"}}
            value={bgColor}
            onChange={(e) => setBgColor(e.target.value)}
            placeholder="门户区背景颜色"
            disabled={saveInProgress}
          />
          <Input
            style={{width: "50%"}}
            value={titleColor}
            onChange={(e) => setTitleColor(e.target.value)}
            placeholder="门户区文字颜色"
            disabled={saveInProgress}
          />
        </Form.Item>
        <Form.Item label="菜单样式">
          <Select
            defaultValue={portalStyle}
            onChange={value => setPortalStyle(value)}
          >
            <Select.Option key="dropdown">弹出下拉式菜单</Select.Option>
            <Select.Option key="drawer">浮出抽屉式菜单</Select.Option>
            <Select.Option key="windows">Windows资源管理器</Select.Option>
          </Select>
          <br/>
          <br/>
          <Checkbox
            checked={portalAuto}
            onChange={e => setPortalAuto(e.target.checked)}
          >自动播放</Checkbox>
          <Checkbox
            checked={PortalHide}
            onChange={e => setPortalHide(e.target.checked)}
          >隐藏门户标题区(按F10键弹出操作菜单)</Checkbox>
        </Form.Item>
        <Form.Item label="颜色样式">
          <Select
            defaultValue={colorStyleMode}
            onChange={value => setColorStyleMode(value)}
            disabled={saveInProgress}
          >
            <Select.Option key=''>-无-</Select.Option>
            {policy.getDefaultStyles().map(({key, title}) => (key!=='custom') && (
              <Select.Option key={key}>{title + ' ' + key}</Select.Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item>
          <Checkbox
            name="is_builtin"
            checked={isBuiltin}
            onChange={(e) => setIsBuiltin(e.target.checked)}>
            设为门户默认菜单
          </Checkbox>
          <Checkbox
            name="is_forbidstyle"
            disabled={!isBuiltin}
            checked={isForbidStyle}
            onChange={(e) => setIsForbidStyle(e.target.checked)}>
            禁止切换样式
          </Checkbox>
        </Form.Item>
      </Form>
      </DynamicComponent>
    </Modal>
  );
}

CreatePortalDialog.propTypes = {
  dialog: DialogPropType.isRequired,
};

export default wrapDialog(CreatePortalDialog);
